package com.cdtu.labpreview.service.impl;

import cn.hutool.db.Session;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdtu.labpreview.common.Result;
import com.cdtu.labpreview.common.UserHolder;
import com.cdtu.labpreview.dto.UserDTO;
import com.cdtu.labpreview.entity.Admin;
import com.cdtu.labpreview.entity.Student;
import com.cdtu.labpreview.entity.Teacher;
import com.cdtu.labpreview.entity.User;
import com.cdtu.labpreview.mapper.AdminMapper;
import com.cdtu.labpreview.mapper.StudentMapper;
import com.cdtu.labpreview.mapper.TeacherMapper;
import com.cdtu.labpreview.mapper.UserMapper;
import com.cdtu.labpreview.service.IUserService;
import com.cdtu.labpreview.util.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Result login(int loginName, String password, int type, HttpSession session) {

        if(type==1){//学生
            LambdaQueryWrapper<Student> lqw=new LambdaQueryWrapper<>();
            lqw.eq(Student::getSno,loginName);
            Student student = studentMapper.selectOne(lqw);
            if(student==null) return  Result.fail("登录失败！请查看用户名密码或角色类型是否有误。") ;
            Boolean isTrue = PasswordEncoder.matches(student.getPassword(), password);
            if(!isTrue) return  Result.fail("登录失败！请查看用户名密码或角色类型是否有误。") ;
            //保存到session
            String sessionId = session.getId();
            session.setAttribute("user"+sessionId,student);

            System.out.println("sessionId:"+sessionId);
            return Result.ok(sessionId);
        }else if(type==2){//老师
            LambdaQueryWrapper<Teacher> lqw=new LambdaQueryWrapper<>();
            lqw.eq(Teacher::getTno,loginName);
            Teacher teacher = teacherMapper.selectOne(lqw);
            if(teacher==null) return  Result.fail("登录失败！请查看用户名密码或角色类型是否有误。") ;
            Boolean isTrue = PasswordEncoder.matches(teacher.getPassword(), password);
            if(!isTrue) return  Result.fail("登录失败！请查看用户名密码或角色类型是否有误。") ;
            //保存到session
            String sessionId = session.getId();
            session.setAttribute("user"+sessionId,teacher);
            return Result.ok(sessionId);
        }else {//管理员
            LambdaQueryWrapper<Admin> lqw=new LambdaQueryWrapper<>();
            lqw.eq(Admin::getAno,loginName);
            Admin admin = adminMapper.selectOne(lqw);
            if(admin==null) return  Result.fail("登录失败！请查看用户名密码或角色类型是否有误。") ;
            Boolean isTrue = PasswordEncoder.matches(admin.getPassword(), password);
            if(!isTrue) return  Result.fail("登录失败！请查看用户名密码或角色类型是否有误。") ;
            //保存到session
            String sessionId = session.getId();
            session.setAttribute("user"+sessionId,admin);
            return Result.ok(sessionId);
        }
    }

    //TODO 添加用户时对密码进行加密
    @Override
    public Result addUser(User user, int type) {

        if(type==1){//学生
            Student student = user.getStudent();
            if(student==null) return Result.fail("添加失败！");
            //对获取到的密码进行加密（加盐+MD5）
            String encodePassword = PasswordEncoder.encode(student.getPassword());
            student.setPassword(encodePassword);
            int flag = studentMapper.insert(student);
            return flag>0 ? Result.ok("添加成功！") : Result.fail("添加失败");
        }else if(type==2){//老师
            Teacher teacher = user.getTeacher();
            if(teacher==null) return Result.fail("添加失败！");
            //对获取到的密码进行加密（加盐+MD5）
            String encodePassword = PasswordEncoder.encode(teacher.getPassword());
            teacher.setPassword(encodePassword);
            int flag = teacherMapper.insert(teacher);
            return flag>0 ? Result.ok("添加成功！") : Result.fail("添加失败");
        }else {
            Admin a = user.getAdmin();
            if(a==null) return Result.fail("添加失败！");
            //对获取到的密码进行加密（加盐+MD5）
            String encodePassword = PasswordEncoder.encode(a.getPassword());
            a.setPassword(encodePassword);
            int flag = adminMapper.insert(a);
            return flag>0 ? Result.ok("添加成功！") : Result.fail("添加失败");
        }
    }


    @Override
    public Result updatePassword(String originPassword, String newPassword) {
        UserDTO userDTO = UserHolder.getUser();
        int userNo = userDTO.getUserNo();
        int type = userDTO.getType();
        if(type==1){
            LambdaQueryWrapper<Student> lqw=new LambdaQueryWrapper<>();
            lqw.eq(Student::getSno,userNo);
            Student student = studentMapper.selectOne(lqw);
            //密码错误，返回提示
            if(!PasswordEncoder.matches(student.getPassword(),originPassword))
                return Result.fail("原始密码错误！");
            //密码正确，修改密码，加密保存到数据库
            String encodeNewPassword = PasswordEncoder.encode(newPassword);
            student.setPassword(encodeNewPassword);
            studentMapper.updateById(student);
            return Result.ok("密码修改成功！");
        }else if(type==2){
            LambdaQueryWrapper<Teacher> lqw=new LambdaQueryWrapper<>();
            lqw.eq(Teacher::getTno,userNo);
            Teacher teacher = teacherMapper.selectOne(lqw);
            //密码错误，返回提示
            if(!PasswordEncoder.matches(teacher.getPassword(),originPassword))
                return Result.fail("原始密码错误！");
            //密码正确，修改密码，加密保存到数据库
            String encodeNewPassword = PasswordEncoder.encode(newPassword);
            teacher.setPassword(encodeNewPassword);
            teacherMapper.updateById(teacher);
            return Result.ok("密码修改成功！");
        }else {
            LambdaQueryWrapper<Admin> lqw=new LambdaQueryWrapper<>();
            lqw.eq(Admin::getAno,userNo);
            Admin admin = adminMapper.selectOne(lqw);
            //密码错误，返回提示
            if(!PasswordEncoder.matches(admin.getPassword(),originPassword))
                return Result.fail("原始密码错误！");
            //密码正确，修改密码，加密保存到数据库
            String encodeNewPassword = PasswordEncoder.encode(newPassword);
            admin.setPassword(encodeNewPassword);
            adminMapper.updateById(admin);
            return Result.ok("修改密码成功！");
        }
    }

    @Override
    public Result resetPassword(int userNo) {
        Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>().eq(Student::getSno, userNo));
        Teacher teacher = teacherMapper.selectOne(new LambdaQueryWrapper<Teacher>().eq(Teacher::getTno, userNo));
        if(student!=null){
            String encode = PasswordEncoder.encode("123456");
            student.setPassword(encode);
            String name = student.getName();
            studentMapper.updateById(student);
            return Result.ok("姓名:"+name+" 密码重置成功！(123456)");
        }else if(teacher!=null){
            String encode = PasswordEncoder.encode("123456");
            teacher.setPassword(encode);
            teacherMapper.updateById(teacher);
            String name = teacher.getName();
            return Result.ok("姓名:"+name+" 密码重置成功！(123456)");
        }else return Result.fail("用户不存在！");
    }

}
